package com.dodoke;

import com.dodoke.beans.User;
import com.dodoke.mappers.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        String resource = "mybatis-config.xml";

        // java 1.7 之前的流操作
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建数据库的会话
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // try - with
        try (SqlSession session = sqlSessionFactory.openSession();) {
            // 该句不是通过构造器去反射实例对象，调用的动态代理模式
            UserMapper mapper = session.getMapper(UserMapper.class);
            //查询所有的信息
            List<User> users = mapper.selectAll();
            System.out.println(users);
            //根据ID查找数据
            User xiaoming = mapper.getUserById(1);
            System.out.println(xiaoming);
            //2个参数查找
            List<User> nameAndAge = mapper.getUserByNameAndAge("xiaoming", 20);
            System.out.println(nameAndAge);

//            Map<String, Object> map = new HashMap<>();
//            map.put("name", "xiaoming");
//            map.put("age", 20);
//
//            List<User> userByNameAndAgeMap = mapper.getUserByNameAndAgeMap(map);
//            System.out.println(userByNameAndAgeMap);

//            List<User> xiaohong = mapper.getUserByNameAndAgeAnnotation("xiaohong", 21);
//            System.out.println(xiaohong);

            //增
            User user1 =new User();
            user1.setName("xiaohuang");
            user1.setAge(18);
            mapper.insertUser(user1);
            session.commit();

            //删除
            mapper.deleteUser(1);
            session.commit();



        }
    }
}

